#ifndef UTILS_H
#define UTILS_H
#include "stdlib.h"
#include "stdio.h"
//handle error
void print_error_msg_and_die(const char *s, ...);

//malloc space of size,if error exit;
void *safe_malloc(size_t size);
void *safe_realloc(void *ptr, size_t size);

//open file in path with mode,if error exit;
FILE *safe_fopen(const char *path, const char *mode);

//open file and copy its content to buf
#define FILE_TO_BUF(filename, fd) do{                           \
    if (fd == -1 && (fd = open(filename, O_RDONLY)) == -1) {    \
        print_error_msg_and_die("/proc not be mounted?");            \
    }                                                           \
    lseek(fd, 0L, SEEK_SET);                                    \
    if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) {        \
        print_error_msg_and_die("%s", filename);                     \
    }                                                           \
    buf[local_n] = '\0';                                        \
}while(0)

#define FILE_TO_BUF2(filename, fd) do{                          \
    lseek(fd, 0L, SEEK_SET);                                    \
    if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) {        \
        print_error_msg_and_die("%s", filename);                     \
    }                                                           \
    buf[local_n] = '\0';                                        \
}while(0)

#endif
